<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\admin\controller;
use app\admin\model\Article as ArticleModel;
use app\admin\model\Cate as CateModel;
use think\File;
use think\Request;

class Article extends Common
{
   
    public function lst(){
        $article=new articleModel();
        //field指定查询字段，查询数据表a中所有字段和数据表b中catename字段
        //alias 设置当前数据表别名为a
        //join 的作用是关联  关联到cate表，cate表的别名定义为b，a表的cateid和b表的id关联查询
        $res=$article->field('a.*,b.catename')->alias('a')->join('cate b','a.cateid=b.id')->paginate('10');

        $this->assign("res",$res);
       
        return view();
      
    }
    public function add(){
        $cates=new CateModel();
        $cateres=$cates->sort();

        $this->assign("cateres", $cateres);
        if(request()->isPost()){
           $data=input('post.');
           $time=date('Y-m-d h:i:s', time());
           $data['date']=$time;
           $Article=new ArticleModel();
           if($Article->save($data)){
               return $this->success("添加成功","lst");
           }else{
               return $this->error("添加失败","lst");
           }
        }
        return view();
    }
    
    
    public function edit(){
        $id=input("id");
        $cates=new CateModel();
        $article=new ArticleModel();
        $cateres=$cates->sort();
        $res=$article->where("id",$id)->find();
        if(request()->isPost()){
            $data=input('post.');
            $time=date('Y-m-d h:i:s', time());
            $data['date']=$time;
            if($article->update($data)){
               return $this->success("更新成功","lst");
           }else{
               return $this->error("更新失败","lst");
           }
        }
        $this->assign("res",$res);
        $this->assign("cateres", $cateres);
        return view();
    }
    public function del(){
          $id=input("id");
          $article=new ArticleModel();
          if($article->destroy($id)){
              return $this->success("删除成功","lst");
          }else{
               return $this->error("删除失败","lst");
          }
    }
    
    public function changeState(){
        $data=[];
        $id=input('id');
        $show=input('show');
        $article=new ArticleModel();
        $res=$article->where('id', $id)->update(['show' => $show]);
        if($res){
            $data['res']='success';
        }else{
            $data['res']='error';
        }
        header('Content-Type:application/json; charset=utf-8');
        return json_encode($data);
    }
    
    
}